package com.atlearn.boot_web.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.URL;

public class ExcelResolve {
    public ExcelResolve() {
    }

    public void readFileJoinTender(String path, HttpServletRequest request) {
        //excel文件路径
        try {
            Workbook wb =getWorkbook(path);

            //开始解析
            //读取sheet 0
            Sheet sheet = wb.getSheetAt(0);
            //第一行是列名，所以不读
            int firstRowIndex = sheet.getFirstRowNum() + 1;
            int lastRowIndex = sheet.getLastRowNum();

            //遍历行
            for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
                Row row = sheet.getRow(rIndex);

                if (row != null) {
                    int indexMin=row.getFirstCellNum();
                    int indexMax=row.getLastCellNum();
                    for (int i = indexMin; i < indexMax; i++) {
                        Cell cell=row.getCell(i);
                        if(cell!=null){
                            System.out.println(cell.toString());
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Workbook getWorkbook(String path) throws Exception{
        String type = path.substring(path.lastIndexOf(".") + 1);
        Workbook wb;
        //根据文件后缀（xls/xlsx）进行判断
        InputStream input = new URL(path).openStream();
        if ("xls".equals(type)) {

            //文件流对象
            wb = new HSSFWorkbook(input);
        } else if ("xlsx".equals(type)) {
            wb = new XSSFWorkbook(input);
        } else {
            throw new Exception("文件 类型错误");
        }
        return wb;
    }

}
